package cn.wen233.common.api;

/**
 * restful风格返回数据包装
 */
public class R<T> {

    private T data;

    private int code;

    private String message;

    private boolean success;

    @Override
    public String toString() {
        return "R{" +
                "data=" + data +
                ", code=" + code +
                ", message='" + message + '\'' +
                ", success=" + success +
                '}';
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public R() {
    }

    private R(T data, int code, String message, boolean success) {
        this.data = data;
        this.code = code;
        this.message = message;
        this.success = success;
    }

    private R(T data, Status status) {
        this.data = data;
        this.message = status.getText();
        this.code = status.getCode();
        this.success = status.isSuccess();
    }

    private R(Status status) {
        this.message = status.getText();
        this.code = status.getCode();
        this.success = status.isSuccess();
    }

    public static <T> R<T> success(T t) {
        return new R<>(t, Status.SUCCESS);
    }

    public static R<?> success() {
        return new R<>(Status.SUCCESS);
    }

    public static R<?> failure(String message) {
        return new R<>(message, Status.FAILURE);
    }

    public static R<?> failure(String message, Status status) {
        return new R<>(message, status);
    }

    public enum Status {

        NO_AUTHORIZATION("该请求无授权", 301, false),

        PERMISSION_DENIED("权限不足", 302, false),

        FAILURE("请求失败", 310, false),

        SUCCESS("请求成功",200, true);

        private String text;

        private int code;

        private boolean success;

        Status(String text, int code, boolean success) {
            this.text = text;
            this.code = code;
            this.success = success;
        }

        public String getText() {
            return text;
        }

        public int getCode() {
            return code;
        }

        public boolean isSuccess() {
            return success;
        }
    }
}
